﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Threading;
using System.Data.SQLite;
using Newtonsoft.Json;
using WebSocket.App_Code.Model;
using WebSocket.App_Code.Common;
using System.Web.SessionState;

namespace WebSocket.Socket
{
    /// <summary>
    /// Socket 的摘要说明
    /// </summary>
    public class Socket : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Server.ScriptTimeout = 1200;
            if (context.Request.QueryString["_type"] != null && context.Request.QueryString["_type"].ToString() != "")
            {
                switch (context.Request.QueryString["_type"].ToString())
                {
                    case "GetUserList": SendUserList(context); break;
                    case "UserLoginIn": UserLoginIn(context); break;
                    case "UserLoginOut": UserLoginOut(context); break;
                    //case "AddListen": SendListenCode(context); break;
                    case "GetNewLoginUser": GetNewLoginUser(context); break;
                    case "GetLoginOutUser": GetLoginOutUser(context); break;
                    default: break;
                }
            }
        }

        ///// <summary>
        ///// 发送标致
        ///// </summary>
        ///// <param name="context"></param>
        //private void SendListenCode(HttpContext context)
        //{
        //    List<string> ListenType = new List<string>();
        //    Users user = context.Session["User"] as Users;
        //    //返回的条件
        //    //1.有改变事件
        //    //2.超过120次,小于1分钟
        //    int WhileCount = 0;
        //    while (ListenType.Count == 0 && WhileCount<100)
        //    {
        //        //判断有没有用户登陆
        //        if ((bool)context.Application["UserLogin_" + user.UserID.ToString()])
        //        {
        //            ListenType.Add("UserLogin");
        //            //收到通知后.改变状态
        //            context.Application.Lock();
        //            context.Application["UserLogin_" + user.UserID.ToString()] = false;
        //            context.Application.UnLock();
        //        }
        //        //判断有没有用户退出
        //        if ((bool)context.Application["UserOut_" + user.UserID.ToString()])
        //        {
        //            ListenType.Add("UserOut");
        //            //收到通知后.改变状态
        //            context.Application.Lock();
        //            context.Application["UserOut_" + user.UserID.ToString()] = false;
        //            context.Application.UnLock();
        //        }
        //        //判断有没有新的信息
        //        if ((bool)context.Application["NewMsg_" + user.UserID.ToString()])
        //        {
        //            ListenType.Add("NewMsg");
        //            //收到通知后.改变状态
        //            context.Application.Lock();
        //            context.Application["NewMsg_" + user.UserID.ToString()] = false;
        //            context.Application.UnLock();
        //        }
        //        WhileCount++;
        //        if (ListenType.Count == 0)
        //        {
        //            Thread.Sleep(500);
        //        }
        //    }
        //    string returnStr = JsonConvert.SerializeObject(ListenType);
        //    context.Response.Write(returnStr);
        //    context.Response.End();
        //}

        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <param name="context"></param>
        private void UserLoginIn(HttpContext context)
        {
            string UserName = context.Request.QueryString["UserName"];
            Users user = new Users();
            user.UserName = UserName;
            user.LoginTime = DateTime.Now;
            user.Add();
            UserLogin(context, user);//用户登陆处理过程
            string resStr = JsonConvert.SerializeObject(user);
            context.Response.Write(resStr);
            context.Response.End();
        }

        /// <summary>
        /// 用户退出
        /// </summary>
        /// <param name="context"></param>
        private void UserLoginOut(HttpContext context)
        {
            Users user = context.Session["User"] as Users;
            context.Application.Lock();
            //通知所有用户,有新的用户登陆
            for (int i = 0; i < context.Application.AllKeys.Length; i++)
            {
                string KeyName = context.Application.AllKeys[i].ToString();
                if (KeyName.Length > 8 && KeyName.Substring(0, 8) == "UserOut_")
                {
                    context.Application[KeyName] = true;
                }
            }
            context.Application.Remove("UserLogin_" + user.UserID.ToString());
            context.Application.Remove("UserOut_" + user.UserID.ToString());
            context.Application.Remove("NewMsg_" + user.UserID.ToString());
            context.Application.UnLock();

            //删除发送给此用户,和此用户发送的所有信息
            MsgToUsers mtu = new MsgToUsers();
            mtu.UserID = user.UserID;
            mtu.Delete(MsgToUsersDeleteType.UserID);

            SocketMsg sm = new SocketMsg();
            sm.UserID = user.UserID;
            sm.Delete(SocketMsgDeleteType.UserID);

            //删除用户
            user.Delete();
        }

        /// <summary>
        /// 发送所有用户列表
        /// </summary>
        /// <param name="context"></param>
        private void SendUserList(HttpContext context)
        {
            Users _user = context.Session["User"] as Users;
            string sqlStr = "select UserID,UserName,LoginTime from Users where UserID<>@UserID and RecordStatus='Active'";
            SQLiteParameter[] sp = { 
                                       new SQLiteParameter("@UserID",DbType.Int32)
                                   };
            sp[0].Value = _user.UserID;
            DataSet ds = SQLiteHelper.GetDataSet(sqlStr, sp);
            List<Users> ListUsers = new List<Users>();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                Users user = new Users();
                user.UserID = int.Parse(ds.Tables[0].Rows[i]["UserID"].ToString());
                user.UserName = ds.Tables[0].Rows[i]["UserName"].ToString();
                user.LoginTime = DateTime.Parse(ds.Tables[0].Rows[i]["LoginTime"].ToString());
                ListUsers.Add(user);
            }
            string resStr = JsonConvert.SerializeObject(ListUsers);
            context.Response.Write(resStr);
            context.Response.End();
        }

        /// <summary>
        /// 发送新登陆的用户列表
        /// </summary>
        /// <param name="context"></param>
        private void GetNewLoginUser(HttpContext context)
        {
            DateTime LastDLTime = DateTime.Parse(context.Request.QueryString["DLLastUserLoginTime"]);
            string sqlStr = "select UserID,UserName,LoginTime from Users where LoginTime>@LoginTime and RecordStatus='Active'";
            SQLiteParameter[] sp = { 
                                       new SQLiteParameter("@LoginTime",DbType.DateTime)
                                   };
            sp[0].Value = LastDLTime;
            DataSet ds = SQLiteHelper.GetDataSet(sqlStr, sp);
            List<Users> ListUsers = new List<Users>();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                Users user = new Users();
                user.UserID = int.Parse(ds.Tables[0].Rows[i]["UserID"].ToString());
                user.UserName = ds.Tables[0].Rows[i]["UserName"].ToString();
                user.LoginTime = DateTime.Parse(ds.Tables[0].Rows[i]["LoginTime"].ToString());
                ListUsers.Add(user);
            }
            string resStr = JsonConvert.SerializeObject(ListUsers);
            context.Response.Write(resStr);
            context.Response.End();
        }

        /// <summary>
        /// 发送用户退出列表
        /// </summary>
        /// <param name="context"></param>
        private void GetLoginOutUser(HttpContext context)
        {
            DateTime LastDLTime = DateTime.Parse(context.Request.QueryString["DLLastUserLoginOutTime"].ToString());
            string sqlStr = "select UserID,LoginOutTime from Users where LoginOutTime>=@LoginOutTime";
            SQLiteParameter[] sp = { 
                                       new SQLiteParameter("@LoginOutTime",DbType.DateTime)
                                   };
            sp[0].Value = LastDLTime;
            DataSet ds = SQLiteHelper.GetDataSet(sqlStr, sp);
            List<Users> ListUsers = new List<Users>();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                Users user = new Users();
                user.UserID = int.Parse(ds.Tables[0].Rows[i]["UserID"].ToString());
                user.LoginOutTime = DateTime.Parse(ds.Tables[0].Rows[i]["LoginOutTime"].ToString());
                ListUsers.Add(user);
            }
            string resStr = JsonConvert.SerializeObject(ListUsers);
            context.Response.Write(resStr);
            context.Response.End();
        }

        /// <summary>
        /// 用户登陆处理
        /// </summary>
        /// <param name="context"></param>
        /// <param name="user"></param>
        private void UserLogin(HttpContext context, Users user)
        {
            //把当前用户放到Session中
            context.Session["User"] = user;

            context.Application.Lock();
            //通知所有用户,有新的用户登陆
            for (int i = 0; i < context.Application.AllKeys.Length; i++)
            {
                string KeyName = context.Application.AllKeys[i].ToString();
                if (KeyName.Length > 10 && KeyName.Substring(0, 10) == "UserLogin_")
                {
                    context.Application[KeyName] = true;
                }
            }
            context.Application.UnLock();
            //初始化自己几个Application
            context.Application["UserLogin_" + user.UserID.ToString()] = false;
            context.Application["UserOut_" + user.UserID.ToString()] = false;
            context.Application["NewMsg_" + user.UserID.ToString()] = false;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    public class SocketListenState
    {
        /// <summary>
        /// 用户登陆
        /// </summary>
        public bool UserLogin;

        /// <summary>
        /// 用户退出
        /// </summary>
        public bool UserOut;

        /// <summary>
        /// 新信息
        /// </summary>
        public bool NewMsg;
    }

    public enum SocketListenType
    { 
        /// <summary>
        /// 用户登陆
        /// </summary>
        UserLogin=0,

        /// <summary>
        /// 用户退出
        /// </summary>
        UserOut=1,

        /// <summary>
        /// 新信息
        /// </summary>
        NewMsg=2
    }

}